import loadFromStorage from "../../utils/load-from-storage"
import getDefaultDB from "./default-db"

const db = loadFromStorage('database', getDefaultDB)

function reset() {
    for (let item in db) {
        delete db[item]
    }
    const defaultDB = getDefaultDB()
    for (let item in defaultDB) {
        db[item] = defaultDB[item]
    }
}

function getTable(tableName) {
    let table = db.tables[tableName]
    if (!table || !(table instanceof Array)) {
        table = db.tables[tableName] = []
    }
    return table
}

function selectOne(tableName, prop, value) {
    return getTable(tableName).find(row => row[prop] === value)
}

function selectByProperty(tableName, prop, value) {
    const table = getTable(tableName)
    return table.filter(row => row[prop] === value)
}

function remove(tableName, prop, value) {
    const table = db.tables[tableName]
    if (!table || !(table instanceof Array)) {
        db.tables[tableName] = []
    } else {
        db.tables[tableName] = table.filter(row => row[prop] !== value)
    }
}

function fuzzyQuery(tableName, prop, value) {
    if (!value.replaceAll) return getTable(tableName).filter(row => row[prop] === value)
    const r = RegExp(`^${value.replaceAll('', '.*?')}$`)
    return getTable(tableName).filter(row => r.test(row[prop]))
}

function insertOne(tableName, row) {
    getTable(tableName).push(row)
}

function selectAll(tableName) {
    return getTable(tableName)
}

function updateOne(tableName, id, prop, value) {
    const table = db.tables[tableName]

    if (!table || !(table instanceof Array)) {
        db.tables[tableName] = []
    } else {
        db.tables[tableName] = table.map((row) => {
            if (row['id'] === id) {
                return { ...row, [prop]: value }
            }
            return row
        })
    }
}

export { selectOne, fuzzyQuery, insertOne, selectAll, remove, reset, selectByProperty, updateOne }